package htlgkr.nodlehs;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class AddSubjectToTeacher extends ListActivity {

	SQLiteDatabase db;
	NodlehsDatabase bridge;
	Hashtable<String, String> selsubs;
	Hashtable<String, String> subsID;
	ArrayList<String> subs = new ArrayList<String>();
	String t_id;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.teachersubjects);
		bridge = new NodlehsDatabase(this);
		db = bridge.getWritableDatabase();
		selsubs = new Hashtable<String, String>();
		subsID = new Hashtable<String, String>();
		loadSub();
		if (savedInstanceState == null) {
			t_id = getIntent().getExtras().getString("Teacher_ID");
		} else {
			t_id = (String) savedInstanceState.getSerializable("STRING_I_NEED");
		}
		Log.i("TID", t_id);
	}

	public void loadSub() {
		Cursor subjects = db.query("subjects", DBSubjectTbl.ALL_COLUMNS,
				"_id>?", new String[] { "0" }, null, null, null);

		while (subjects.moveToNext()) {
			subsID.put(subjects.getString(1), subjects.getString(0));
			subs.add(subjects.getString(1));
		}
		if (subs.isEmpty()) {
			subs.add("@string/noSubjects");
		}
		ArrayAdapter<String> subjectAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, subs);
		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		setListAdapter(subjectAdapter);

	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		if (selsubs.containsKey(position + "")) {
			selsubs.remove(position + "");
		} else {
			selsubs.put(position + "", l.getItemAtPosition(position).toString());
		}
		Log.i("ELEMENT", l.getItemAtPosition(position).toString());
	}

	public void addSubtoTeacher(final View v) {
		long id = 0;
		String[] subjects = new String[selsubs.size()];
		selsubs.values().toArray(subjects);
		
		db.beginTransaction();
		try {
			for (int i = 0; i < subjects.length; i++) {
				SQLiteStatement stmt = db.compileStatement(DBRefSubTeaTbl.SQL_INSERT);
				String s_id = subsID.get(subjects[i]);
				Log.i("Sub", s_id);
				stmt.bindString(1, t_id);
				stmt.bindString(2, s_id);
				id = stmt.executeInsert();
			}
			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("DBInsert SubTeacher", e.getMessage().toString());
		} finally {
			db.endTransaction();
			db.close();
		}
		Log.i("SubTeacherActivity", id + "");
		//Log.i("SubTeacherActivity", id + "");
	}

}
